<template>
  <div class="user-profile">
    <h1>{{ title }}</h1>
    <div v-if="loading">Loading...</div>
    <div v-else>
      <p>Name: {{ user.name }}</p>
      <p>Age: {{ userAge }}</p>
      <p>Email: {{ user.email }}</p>
      <button @click="incrementAge">Increment Age</button>
      <button @click="fetchUserData">Refresh</button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount } from 'vue';

export default {
  name: 'TestVueComponent',
  setup() {
    // 响应式数据
    const title = ref('User Profile');
    const loading = ref(false);
    const user = reactive({
      name: 'John Doe',
      age: 25,
      email: 'john@example.com'
    });

    // 计算属性
    const userAge = computed(() => {
      return user.age + ' years old';
    });

    const isAdult = computed(() => {
      return user.age >= 18;
    });

    // 方法
    const incrementAge = () => {
      user.age++;
    };

    const fetchUserData = async () => {
      loading.value = true;
      try {
        const response = await fetch('/api/user');
        const userData = await response.json();
        Object.assign(user, userData);
      } catch (error) {
        console.error('Error fetching user:', error);
      } finally {
        loading.value = false;
      }
    };

    const validateUser = () => {
      return user.name && user.email;
    };

    // 监听器
    watch(() => user.age, (newAge, oldAge) => {
      console.log(`Age changed from ${oldAge} to ${newAge}`);
    });

    // 生命周期钩子
    onMounted(() => {
      console.log('Component mounted');
      fetchUserData();
    });

    onBeforeUnmount(() => {
      console.log('Component will be destroyed');
    });

    // 返回需要在模板中使用的数据和方法
    return {
      title,
      loading,
      user,
      userAge,
      isAdult,
      incrementAge,
      fetchUserData,
      validateUser
    };
  }
}
</script>

<style scoped>
.user-profile {
  padding: 20px;
  border: 1px solid #ccc;
}
</style>